# WTF Engine - Game entry point
# Woosta Table Football 2008

from WtfEngine import *
import WtfGui;
import WtfAudio;
from scripts import WtfObjs;
from scripts import WtfApp;
from scripts import WtfHud;

DebugPrint("Script Begins");

mouseSensitivity = 0.0025
game = 0;
gWm = 0;
gMenu = 0;
gTable = 0;

#
# TODO:
# Game event handlers & game logic
#

class Menu(GameState):
	def __init__(self):
		GameState.__init__(self);
		
	
class Interface(WtfGui.ScreenOverlay):
	def __init__(self):
		
		WtfGui.ScreenOverlay.__init__(self);
		
		ctrOpts = WtfGui.LayoutContainerCreationOptions();
		
		# Create bars
		self.topBar = WtfGui.LayoutContainer(ctrOpts, 0);
		
		self.scoreBoard = WtfGui.Label("0 - 0", WtfGui.Font("v_gui_font"));
		self.scoreBoard.ExpandToText();
						
		# Add elements
		self.AddChild(WtfGui.LayoutPositioner(self.topBar, WtfGui.CentrePositioner(), WtfGui.TopPositioner()));

		self.Init();
		self.topBar.AddChild(self.scoreBoard);
		
	def setGoals(self, a, b):
		self.scoreBoard.caption = str(a) + " - " + str(b);
		self.scoreBoard.ExpandToText();
	
	
class Game(CustomGameState):
	def __init__(self, table):
		CustomGameState.__init__(self);
		
		Renderer.GetInst().camera = Camera(Vector(0,100,50),Vector(0,0,0),Vector(0,1,0));
		
		self.interface = Interface();
		
		self.plyrGoals = 0;
		self.otherGoals = 0;
		self.hasScored = 0;
		
		self.table = table;
		self.table.reset();
		
		self.rowHist = [];
		self.row = -1;
		
		self.keyMap = {
			'z': EventHandler(lambda x: self.toggleRow(x, 0)),
			'x': EventHandler(lambda x:	self.toggleRow(x, 1)),
			'c': EventHandler(lambda x:	self.toggleRow(x, 2)),
			'v': EventHandler(lambda x:	self.toggleRow(x, 3)),
			'a': EventHandler(lambda x: self.toggleRow(x, 4)),
			's': EventHandler(lambda x:	self.toggleRow(x, 5)),
			'd': EventHandler(lambda x:	self.toggleRow(x, 6)),
			'f': EventHandler(lambda x:	self.toggleRow(x, 7))
		};
		
		self.ball = WtfObjs.Ball();
		
		# Goal handlers
		self.BindEvent(ObjectInteractionEvent(self.ball, table.goal1), EventHandler(self.goalInAway));
		self.BindEvent(ObjectInteractionEvent(self.ball, table.goal2), EventHandler(self.goalInHome));
		
		# Mouse move event handler
		self.BindEvent(MouseMoveEvent(), EventHandler(self.moveRow));
		self.BindEvent(KeyDownEvent(InputKey(ord(' '))), EventHandler(lambda e: resetBall()));

		# Write keymap
		for key in self.keyMap.keys():
			k = InputKey(ord(key))
			self.BindEvent(KeyDownEvent(k), self.keyMap[key]);
			self.BindEvent(KeyUpEvent(k), self.keyMap[key]);

	def StartGame(self):
		self.interface.Init();
		getKernel().PushGameState(game);
		
	def goalInHome(self, e):
		if self.hasScored == 0:
			DebugPrint("AWAY GOAL");
			self.otherGoals = self.otherGoals + 1;
			self.interface.setGoals(self.plyrGoals, self.otherGoals);
			self.hasScored = 1;
			
	def goalInAway(self, e):
		if self.hasScored == 0:
			self.plyrGoals = self.plyrGoals + 1;
			DebugPrint("HOME GOAL [" + str(self.plyrGoals) + "]");
			self.interface.setGoals(self.plyrGoals, self.otherGoals);
			self.hasScored = 1;
		
	def moveRow(self, e):
		if self.row != -1:
			self.table.rows[self.row].move((e.dy) * mouseSensitivity)
			self.table.rows[self.row].rotate((e.dx) * mouseSensitivity)
	
	
	#
	# Set row i to the moving row
	#
	def startRow(self, i):
		DebugPrint("St " + str(i));
		
		if self.row != i:
			if self.rowHist.count(i) > 0:
				self.rowHist.remove(i);
			self.rowHist.append(self.row);
			self.row = i;
		
	
	#
	# Stop moving row i
	#
	def endRow(self, i):
		DebugPrint("End " + str(i));
		
		if self.row == i:
			self.row = self.rowHist.pop();
		else:
			self.rowHist.remove(i);
		
		
	def toggleRow(self, e, i):
		if isinstance(e, KeyDownEvent):
			self.startRow(i);
		else:
			self.endRow(i);

	def Enable(self):
		DebugPrint("Enabling Game..");
		InputHandler.GetInst().CaptureAllInput(1);
		DebugPrint("Game Enabled");

class GameOptions(WtfGui.Window):
	def __init__(self, game):
		WtfGui.Window.__init__("Game Options");
		
		self.game = game;
	
	def Start(self):
		self.game.Start();
		
		
def mainMenu():
	global menu;
	menu = Menu();
	getKernel.ForkGameState(menu);
	
def startGame():
	global game; global gTable;
	game = Game(gTable);
	getKernel().PushGameState(game);
	menu = GameMenu();
	menu.BindToEvent(KeyDownEvent(InputKey(27)));

def resetBall():
	global game;
	game.ball.reset();
	game.hasScored = 0;

class Options(WtfGui.Window):
	def __init__(self, font):
		WtfGui.Window.__init__(self, "Options");
		
		self.text = WtfGui.Label("Coming soon", font);
		self.AddChild(self.text);
		
		self.text.ExpandToText();
		
		self.cp = WtfGui.ColourPicker();
		self.cp.size = iVector2D(100, 250);
		self.AddChild(self.cp);
		
class GuiHelp(WtfGui.Window):
	def __init__(self, font):
		WtfGui.Window.__init__(self, "GUI Help");
		
		self.text = WtfGui.Label("Keyboard Shortcuts\n ESC - close the GUI\n Ctrl + Tab - switch windows\n Ctrl + W - close window\n Tab - cycle forwards\n Shift + Tab - cycle backwards", font);
		self.AddChild(self.text);
		
		self.text.ExpandToText();

def spawnUtility(wm):
	wnd = WtfGui.Window("Utility");
	wnd.innerSize = iVector2D(400, 400);
	scene = WtfGui.Scene(
		Camera(Vector(0, 100, 100), Vector(0, -100, -100), Vector(0, 1, 0)),
		iVector2D(400, 350)
	);
	btnSShot = WtfGui.Button(
		Function(lambda: scene.frameBuffer.Write("screenie.png")),
		"Save Screenshot", WtfGui.Font("v_gui_font")
	);
	
	wnd.AddChild(scene);
	
	btnSShot.Move(0, 350);
	btnSShot.size = iVector2D(200, 30);
	wnd.AddChild(btnSShot);
	
	wm.AddWindow(wnd, 1);


class GameMenu(WtfHud.GameMenu):
	def __init__(self):
		WtfHud.GameMenu.__init__(self, {
			'Options': (lambda: self.AddWindow(Options(font), 1)),
			'Developers Console': (lambda: self.SpawnConsole()),
			'Save Game': (lambda: GameManager.GetInst().SaveGameToFile("f.txt")),
			'Load Game': (lambda: GameManager.GetInst().LoadGameFromFile("f.txt")),
			'Exit': (lambda: exit())
		}, ['Developers Console', 'Save Game', 'Load Game', 'Exit']);

def initGUI():
	font = WtfGui.Font("v_gui_font");
	
	# Set colours
	WtfGui.Colour("v_gui_bgColour").value = ColourVal(0, 0, 0, 0.5);
	WtfGui.Colour("v_gui_windowBgColour").value = ColourVal(0.3, 0.29, 0.29, 1.0);
	WtfGui.Colour("v_gui_wmBg").value = ColourVal(0.2,0.2,0.2,0.5);
	
	# Create menu
	gWm = WtfHud.TitleMenu({
		'New Game': lambda: startGame(),
		'Network Game': lambda: WtfLAN.showLobby(gWm),
		'Options': lambda: gWm.AddWindow(Options(font), 1),
		'Developers Console': lambda: gWm.SpawnConsole,
		'WtfEdit': lambda: WtfApp.Load("wtfedit", {'wm': gWm}),
		'WtfRTS': (lambda: WtfApp.Load("rts", {"wm": gWm})),
		'Exit': lambda: exit()
	}, ['New Game','Network Game','Options','Developers Console','WtfEdit','WtfRTS','Exit']);
	gWm.BindToEvent(KeyDownEvent(InputKey(27,0)));

	# Activate the GUI
	gWm.WmToggle();


def startIntro():
	r = Renderer.GetInst();
	backdrop = WtfGui.ScreenOverlay();
	
	wm = WtfGui.WindowManager();
	wm.WmToggle();
	
	img = WtfGui.Image(TextureRef("media/images/DynamoGameStudios.png"));
	img.innerSize = iVector2D(500,360);
	wm.AddChild(WtfGui.LayoutPositioner(img, WtfGui.CentrePositioner(), WtfGui.CentrePositioner()));
	
	opts = WtfGui.ColourBackgroundCreationOptions();
	c = WtfGui.ColourSetting("intro_backdrop_colour", ColourVal(0,0,0,1.0));
	opts.colour = c;
	backdrop.background = WtfGui.BackgroundSetting("intro_backdrop",
		WtfGui.ColourBackground(opts));
	backdrop.size = wm.size;
	backdrop.Init();
	
	def startMenu():
		backdrop.Remove();
		wm.WmToggle();
		initGUI();
	
	def logoSwitch(logo, f):
		img.src = TextureRef(logo);
		c.interpolate(ColourVal(0,0,0,0), 3.5, Function(f));
	
	def out(f):
		c.interpolate(ColourVal(0,0,0,1), 3.5, Function(f));
	
	fIn = (lambda: c.interpolate(ColourVal(0,0,0,0), 3.5, Function(
		lambda: out(lambda: logoSwitch("media/images/PoweredBy.png",
			lambda: out(lambda: logoSwitch("media/images/WTF.png", startMenu))))
		)));
	c.interpolate(ColourVal(0,0,0,1), 3.0, Function(fIn));



## Initialization starts here

DebugPrint("Window manager initialized");

gTable = WtfObjs.Table();

font = WtfGui.Font("v_gui_font");
#initGUI();
startIntro();
# WtfLAN.test();
#WtfApp.Load("tbs", []);
#WtfApp.Load("synth", []);

# Intro sound
#WtfAudio.AudioStream(WtfAudio.VorbisData("media/sfx/wtfgames.ogg")).Play(False);

DebugPrint("Game initialized!");
